package DAO;/*
@author joker
@create 2022-03-08 23:14
开发BasicDAO, 是其他DAO类的父类
*/


import Utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BasicDAO<T> {//泛型指定具体类型
    private final QueryRunner qr = new QueryRunner();

    //开发一个通用的dml方法,针对任意的表
    public int update(String sql, Object... parameters) {
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            int update = qr.update(connection, sql, parameters);//parameters对应sql中的?
            return update;
        } catch (SQLException e) {//sewlect * from actor where id =? ? ? ?
            throw new RuntimeException();//把一个编译异常-->运行异常
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }

    /*
     * sql语句,可以有?号
     * clazz 传入一个类的Class对象
     * parameters 可变性惨,传入?的具体值,可以是多个
     * return值: 根据Actor.class,返回对应的ArrayList集合*/
    //返回多个对象(查询的结果是多行的),针对任意的表
    public List<T> queryMultiply(String sql, Class<T> clazz, Object... parameters) {
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException();//把一个编译异常-->运行异常
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }

    //查询单行结果的通用方法
    public T querySingle(String sql, Class<T> clazz, Object... parameters) {
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException();//把一个编译异常-->运行异常
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }

    //查询单行单列的方法, 即返回单值的方法
    public Object queryScalar(String sql, Object... parameters) {
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection, sql, new ScalarHandler<>(), parameters);
        } catch (SQLException e) {
            throw new RuntimeException();//把一个编译异常-->运行异常
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }

}
